package com.zzyweb.rentalcarsys.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.zzyweb.rentalcarsys.entity.Menu;
import com.zzyweb.rentalcarsys.mapper.MenuMapper;
import com.zzyweb.rentalcarsys.service.MenuService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * @author zhiyi
 * @date 10/9/25
 **/
@Service
public class MenuServiceImpl implements MenuService {
    @Autowired
    MenuMapper menuMapper;
    @Override
    public List<Menu> getAll() {
        List<Menu> menus = menuMapper.selectList(null);
        return getMenuTree(menus);
    }

    @Override
    public void addMenu(Menu menu) {
        if (menu.getParentId()==null) {
            menu.setParentId(0);
        }
        menuMapper.insert(menu);
    }

    @Override
    public void modifyMenu(Menu menu) {
        menuMapper.updateById(menu);
    }

    @Override
    public void deleteMenu(Integer menuId) {
        QueryWrapper<Menu> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("parent_id", menuId);
        List<Menu> menus = menuMapper.selectList(queryWrapper);
        if (!menus.isEmpty()) {
            for (Menu menu : menus) {
                menuMapper.deleteById(menu.getMenuId());
            }
        }
        menuMapper.deleteById(menuId);
    }

    @Override
    public List<Menu> getMenusByUsername(String username) {
        List<Menu> menus = menuMapper.selectMenuByUserName(username);
        return getMenuTree(menus);
    }

    private List<Menu> getMenuTree(List<Menu> menuList) {
        //按照parentId进行分类
        Map<Integer, List<Menu>> parentMap= menuList.stream().collect(Collectors.groupingBy(Menu::getParentId));
        //找出根节点菜单
        List<Menu> rootMenus = menuList.stream().filter(menu -> menu.getParentId() == null || menu.getParentId().equals(0))
                .collect(Collectors.toList());
        rootMenus.forEach(menu -> attachChildren(menu,parentMap));
        return rootMenus;
    }

    private void attachChildren(Menu parent, Map<Integer, List<Menu>> parentMap) {
        List<Menu> children = parentMap.get(parent.getMenuId());
        if (children != null && !children.isEmpty()) {
            parent.setChildren(children);
            children.forEach(child -> attachChildren(child, parentMap));
        }
    }
}
